package com.fire.security.service.impl;


import com.fire.security.domain.Articles;
import com.fire.security.domain.Result;
import com.fire.security.mapper.ArticlesMapper;
import com.fire.security.service.ArticleService;
import com.fire.security.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;


import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticlesMapper articlesMapper;

    //注入redis模板
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //存入数据库中的路径
    private String accessPath = "http://localhost:8088/img/";
    @Override
    public Result insertArticles(Articles articles) {

        //处理上传的图片的访问地址 -- /img/图片名称
        articles.setImageUrl(accessPath+articles.getImageUrl());

        int i = articlesMapper.insert(articles);
        if(i>0) {
            if (!stringRedisTemplate.hasKey("todayArticles")) {
                stringRedisTemplate.opsForValue().set("todayArticles", String.valueOf(1), DateUtils.getTimeDifference(new Date()), TimeUnit.SECONDS);
            } else {
                int todayViewerNumber = Integer.parseInt(stringRedisTemplate.opsForValue().get("todayArticles"));
                stringRedisTemplate.opsForValue().set("todayArticles", String.valueOf(todayViewerNumber + 1), DateUtils.getTimeDifference(new Date()), TimeUnit.SECONDS);
            }
            return Result.ok("添加文章成功！");
        }

        return Result.err(Result.CODE_ERR_BUSINESS, "添加文章失败！");
    }

    //删除图片
    @Override
    public boolean deleteImg(String fileName) {
        try{
            //拿到图片上传到的目录(类路径classes下的static/img/upload)的File对象
            File uploadDirFile = ResourceUtils.getFile("classpath:static/img");
            //拿到图片上传到的目录的磁盘路径
            String uploadDirPath = uploadDirFile.getAbsolutePath();
            System.out.println(uploadDirPath);
            //拿到图片保存到的磁盘路径
            String fileUploadPath = uploadDirPath + "\\" + fileName.replace("http://localhost:8088/img/","");
            System.out.println(fileUploadPath);
            //System.out.println(img_path);//输出测试一下文件路径是否正确
            File file = new File(fileUploadPath);
            if (file.exists()) {//文件是否存在
                if (file.delete()) {//存在就删了，返回1
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }catch (IOException e){
            e.printStackTrace();
            return false;
        }
    }

    //删除文章
    @Override
    public Result deleteArticles(Integer articleId) {
        Articles articles = articlesMapper.selectById(articleId);
        if (articlesMapper.deleteById(articleId) == 1){
            if (deleteImg(articles.getImageUrl())){
                return Result.ok("删除文章成功！");
            }else {
                return Result.err(Result.CODE_ERR_BUSINESS,"图片删除失败！");
            }
        }else {
            return Result.err(Result.CODE_ERR_BUSINESS,"删除文章失败！");
        }
    }

    //更新文章
    @Override
    public Result updateArticles(Articles articles) {
        if(!articles.getImageUrl().startsWith(accessPath)){
            articles.setImageUrl(accessPath+articles.getImageUrl());
        }
        int i = articlesMapper.updateByIdSelective(articles);
        if (i == 1){
            return Result.ok("更新文章成功！");
        }else {
            return Result.err(Result.CODE_ERR_BUSINESS,"更新文章失败！");
        }
    }

    //添加观看量
    @Override
    public Result addNumber(Integer articleId) {
        Articles articles = articlesMapper.selectById(articleId);
        int i = articlesMapper.updateViewerNumber(articleId, articles.getViewerNumber()+1);
        if (i == 1){
            if (!stringRedisTemplate.hasKey("todayViewer")){
                stringRedisTemplate.opsForValue().set("todayViewer", String.valueOf(1), DateUtils.getTimeDifference(new Date()), TimeUnit.SECONDS);
            }else {
                int todayViewerNumber = Integer.parseInt(stringRedisTemplate.opsForValue().get("todayViewer"));
                stringRedisTemplate.opsForValue().set("todayViewer", String.valueOf(todayViewerNumber+1), DateUtils.getTimeDifference(new Date()), TimeUnit.SECONDS);
            }
            return Result.ok("添加观看量成功！");
        }else {
            return Result.err(Result.CODE_ERR_BUSINESS,"添加观看量失败！");
        }
    }

    //查询文章列表
    @Override
    public List<Articles> getArticlesList(Articles articles) {
        List<Articles> articlesList = articlesMapper.selectArticles(articles);
        return articlesList;
    }

    @Override
    public Result selectTodayArticles() {
        Articles articles = new Articles();
        articles.setStartTime(new Date());
        List<Articles> articlesList = articlesMapper.selectArticles(articles);
        return Result.ok(articlesList.size());
    }
}
